React 重复渲染
React 什么时候造成重复渲染?
当 React 中一个组件进行更新时,它的所有子组件都会进行重新渲染,即便子组件的 props 并未发生任何改变。
React 为什么会重复渲染?
答案:由于默认渲染行为的问题
在 React Component 的生命周期中,有一个 shouldComponentUpdate 方法。这个方法默认返回值是 true。
这意味着就算没有改变组件的 props 或者 state,也会导致组件的重绘。这就经常导致组件因为不相关数据的改变导致重绘,这极大的降低了 React 的渲染效率。
比如下面的例子中,任何 options 的变化,甚至是其他数据的变化都可能导致所有 cell 的重绘。
//Table Component
{this.props.items.map(i =>
<Cell data={i} option={this.props.options[i]} />
)}
重写 shouldComponentUpdate 为了避免这个问题,我们可以在 Cell 中重写 shouldComponentUpdate 方法,只在 option 发生改变时进行重绘。
class Cell extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
if (this.props.option === nextProps.option) {
return false;
} else {
return true;
}
}
}
这样每个 Cell 只有在关联 option 发生变化时进行重绘。